# -*- coding: utf-8 -*-
'''andutils.py: some usefull UI functions for Android
this module is designed to work with SL4A.

© Dmitri Brechalov, 2011
'''

import sys
import os.path
import android

_droid = android.Android()

def message(title, msg):
    '''display simple dialog with title, message and close button
    '''
    _droid.dialogCreateAlert(title, msg)
    _droid.dialogSetNeutralButtonText('Close')
    _droid.dialogShow()
    _droid.dialogGetResponse()

def info(msg):
    '''display info message
    '''
    message('Info', msg)

def error(msg):
    '''display error message
    '''
    message('Error', msg)

def toast(msg):
    '''display "toast" - short popup message
    '''
    _droid.makeToast('All done')

def scandir(d, filt='*'):
    '''returnist with contents of the directory d
    ordered alphabetically, directories first
    directory names are preceeded with slash
    optionaly file names cab be filtered by filt
    '''
    from fnmatch import fnmatch
    flist = list()
    dlist = list()
    for f in os.listdir(d):
        p = os.path.join(d, f)
        if f.startswith('.'): continue
        if os.path.isdir(p):
            dlist.append('/' + f)
        else:
            if fnmatch(f, filt):
                flist.append(f)
    dlist.sort()
    flist.sort()
    result = ['..'] + dlist + flist
    return result

def filedialog(title='Open File', directory=None, filter='*', usedir=False):
    '''simple dialog with filelist of the directory (current dir by default)
    optionally filtered by wildcards, allows browsing through directory structure
    usedir=True - allows select directory name (includes special item <Select this dir>
    returns file path or None
    '''
    thisdiritem = '<Select this dir>'
    if not directory:
        directory = os.path.curdir
    elif not os.path.isdir(directory):
        directory = os.path.split(directory)[0]
    directory = os.path.abspath(directory)
    while True:
        flist = scandir(directory, filter)
        if usedir:
            flist = [thisdiritem] + flist
        _droid.dialogCreateInput('%s: %s' % (title, directory))
        _droid.dialogSetItems(flist)
        _droid.dialogShow()
        response = _droid.dialogGetResponse().result
        if response.has_key('canceled') and response['canceled']:
            _droid.dialogDismiss()
            return None
        selected = flist[response['item']]
        if selected == '..':
            directory = os.path.split(directory)[0]
        elif selected.startswith('/'):
            directory = os.path.join(directory, selected[1:])
        elif selected == thisdiritem:
            _droid.dialogDismiss()
            return directory
        else:
            _droid.dialogDismiss()
            return os.path.join(directory, selected)

def getFileName(title, prompt, fname='', filter='*', usedir=False):
    '''common file dialog with which allows user to type filename
    and/or browse through directory structure
    returns file path or None
    '''
    while True:
        _droid.dialogCreateInput(title, prompt, fname)
        _droid.dialogSetPositiveButtonText('OK')
        _droid.dialogSetNeutralButtonText('Browse')
        _droid.dialogSetNegativeButtonText('Cancel')
        _droid.dialogShow()
        ans = _droid.dialogGetResponse().result
        _droid.dialogDismiss()
        if ans.has_key('canceled') and ans['canceled'] \
          or ans.has_key('which') and ans['which'] == 'negative':
            return None
        if ans.has_key('which') and ans['which'] == 'positive':
            return ans['value']
        if ans.has_key('which') and ans['which'] == 'neutral':
            fname = filedialog(title, ans['value'], filter, usedir)

if __name__ == '__main__':
    message('Test', 'Testing everything...')
    fn = getFileName('Open File', 'File Name:')
    if fn:
        info('%s selected' % fn)
    else:
        error('Nothing selected')
    toast('All done.')
    
